package eleven2Twenty;

/**
 * 求base的exponent次方
 * Created by Wongy on 2018/3/14.
 */
public class Eleven11 {
    private static double power(double base, int exponent) {
        if (equal(base, 0.0) && exponent < 0) {
            throw new RuntimeException("0的负数次幂没有意义");
        }
        return exponent < 0 ? powerWithExponent2(1.0 / base, -exponent) : powerWithExponent2(base, exponent);
    }

    private static double powerWithExponent(double base, int exponent) {
        double result = 1.0;
        for (int i = 1; i <= exponent; i++) {
            result *= base;
        }
        return result;
    }

    private static double powerWithExponent2(double base, int exponent) {
        if (exponent == 0) {
            return 1;
        }
        if (exponent == 1) {
            return base;
        }
        double result = powerWithExponent2(base, exponent >> 1);
        result *= result;
        if ((exponent & 1) == 1) {
            result *= base;
        }
        return result;
    }

    private static boolean equal(double num1, double num2) {
        return Math.abs(num1 - num2) < 0.000001;
    }

    public static void main(String[] args) {
        double result = power(2, 2);
        System.out.println("Eleven11.main , 44 : " + result);
    }
}
